package com.houhanzhi.controller;

import com.houhanzhi.annotation.RepeatSubmit;
import com.houhanzhi.constant.RedisKey;
import com.houhanzhi.controller.request.ConfirmOrderRequest;
import com.houhanzhi.controller.request.ProductOrderPageRequest;
import com.houhanzhi.enums.BizCodeEnum;
import com.houhanzhi.enums.ClientTypeEnum;
import com.houhanzhi.enums.ProductOrderPayTypeEnum;
import com.houhanzhi.interceptor.LoginInterceptor;
import com.houhanzhi.response.JsonData;
import com.houhanzhi.service.ProductOrderService;
import com.houhanzhi.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/order/v1")
@Slf4j
public class ProductOrderController {

    @Autowired
    private ProductOrderService productOrderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 下单前获取令牌用于防重提交
     *
     * @return
     */
    @GetMapping("/token")
    public JsonData getOrderToken() {
        Long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
        String token = CommonUtil.getStringNumRandom(32);
        String key = String.format(RedisKey.SUBMIT_ORDER_TOKEN_KEY, accountNo, token);

        // 令牌有效时间30分钟
        redisTemplate.opsForValue().set(key, Thread.currentThread().getName(), 30, TimeUnit.MINUTES);

        return JsonData.buildSuccess(token);
    }


    /**
     * 分页
     *
     * @param request
     * @return
     */
//    @RepeatSubmit(limitType = RepeatSubmit.Type.TOKEN)
//    @RepeatSubmit(limitType = RepeatSubmit.Type.PARAM)
    @PostMapping("/page")
    public JsonData page(@RequestBody ProductOrderPageRequest request) {
        Map<String, Object> map = productOrderService.page(request);
        return JsonData.buildSuccess(map);
    }

    /**
     * 查询订单状态
     *
     * @param outTradeNo
     * @return
     */
    @GetMapping("/query_state")
    public JsonData queryState(@RequestParam(value = "out_trade_no") String outTradeNo) {
        String state = productOrderService.queryProductOrderState(outTradeNo);
        return StringUtils.isEmpty(state) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(state);
    }

    /**
     * 下单
     * 经防重复提交令牌验证：@RepeatSubmit(limitType = RepeatSubmit.Type.TOKEN)
     *
     * @param request
     * @param response
     */
    @RepeatSubmit(limitType = RepeatSubmit.Type.TOKEN)
    @PostMapping("/confirm")
    public void confirmOrder(@RequestBody ConfirmOrderRequest request, HttpServletResponse response) {
        JsonData jsonData = productOrderService.confirmOrder(request);
        if (jsonData.getCode() == 0) {
            // 设备类型
            final String clientType = request.getClientType();
            // 支付类型
            final String payType = request.getPayType();
            // 支付宝支付，跳转网页，sdk除外
            if (ProductOrderPayTypeEnum.ALI_PAY.name().equalsIgnoreCase(payType)) {
                if (ClientTypeEnum.APP.name().equalsIgnoreCase(clientType)) {
                    // TODO
                } else if (ClientTypeEnum.PC.name().equalsIgnoreCase(clientType)) {
                    CommonUtil.sendHtmlMessage(response, jsonData);
                } else if (ClientTypeEnum.H5.name().equalsIgnoreCase(clientType)) {
                    // TODO
                }
            } else if (ProductOrderPayTypeEnum.WECHAT_PAY.name().equalsIgnoreCase(payType)) {
                // 微信支付
                CommonUtil.sendJsonMessage(response, jsonData);
            } else if (ProductOrderPayTypeEnum.BANK.name().equalsIgnoreCase(payType)) {
                // TODO 银行卡
            }
        } else {
            log.error("创建订单失败:{}", jsonData.toString());
            CommonUtil.sendJsonMessage(response, jsonData);
        }
    }

}
